package com.elastic.domain;

import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public class Factory {

    /**
     * 查询多边形内数据
     * @param field
     * @param points
     * @return
     * @throws Exception
     */
    public BoolQueryBuilder builtPolygonQuery(String field, List<GeoPoint> points) throws Exception {
        if (points == null ||points.size() <=0) {
            throw new Exception("bad args of geo points");
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        QueryBuilder matchQueryBuilder = QueryBuilders.geoPolygonQuery(field, points);
        boolQueryBuilder.should(matchQueryBuilder);
        return boolQueryBuilder;
    }

    /**
     * 查询矩形框内数据
     * @param field
     * @param point1
     * @param point2
     * @return
     * @throws Exception
     */
    public BoolQueryBuilder builderBoundingBox(String field, GeoPoint point1, GeoPoint point2) throws Exception {
        if (point1 == null ||point2 == null) {
            throw new Exception("bad args of geo points");
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        QueryBuilder matchQueryBuilder = QueryBuilders.geoBoundingBoxQuery(field).setCorners(point1, point2);
        boolQueryBuilder.should(matchQueryBuilder);
        return boolQueryBuilder;
    }

    /**
     * 查询圆内数据
     * @param field
     * @param distance
     * @param point
     * @return
     * @throws Exception
     */
    public BoolQueryBuilder builderDistance(String field, String distance, GeoPoint point) throws Exception {
        if (point == null) {
            throw new Exception("bad args of geo points");
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        QueryBuilder matchQueryBuilder = QueryBuilders.geoDistanceQuery(field).point(point).distance(distance, DistanceUnit.METERS);
        boolQueryBuilder.should(matchQueryBuilder);
        return boolQueryBuilder;
    }

}